<!doctype html>
<html lang="en">
<head>
    <title>Sse推送测试</title>
</head>
<body>
<div>
    <label for="userId">请输入连接id：</label>
    <input type="text" id="userId" placeholder="当前用户ID" value="">
</div>
<span>
    <button id="connect" type="button" onclick="connect()">连接</button>
    <button id="disconnect" type="button" disabled="disabled" onclick="disconnect()">断开连接</button>
    <button id="openChat" type="button" disabled="disabled" onclick="openChat()">开启聊天功能</button>
</span>

<div id="chatBody" style="display: none">
    <div>
        <label for="targetId">请输入对方id：
            <input type="text" id="targetId" placeholder="对方用户ID" value="">
        </label>
        <input type="text" id="msg" placeholder="请输入消息.." value="">
    </div>
    <div>
        <button id="sendMsgButton" type="button" onclick="sendMsg()">发送消息</button>
    </div>
</div>
<hr>
<div id="data"></div>
</body>
</html>
<script>
    let source;
    let baseUrl = 'http://localhost:80';  //nginx 80反向代理8080,8081

    function disconnect() {
        const userId = document.getElementById('userId').value;
        if (source) {
            source.close();
        }
        sendGetRequest(baseUrl + '/sse/end?clientId=' + userId)
            .then(response => {
                console.log(response);
                setConnected(false)
                document.getElementById('openChat').style.display = 'block';
            });
    }

    function connect() {
        const userId = document.getElementById('userId').value;
        if (!userId) {
            alert('用户唯一ID未填写!');
            return;
        }

        if (window.EventSource) {
            source = new EventSource(baseUrl + '/sse/start?clientId=' + userId);

            <!-- 添加一个开启回调 -->
            source.onopen = function (event) {
                let text = document.getElementById('data').innerText;
                text += '\nonopen: 连接成功!';
                document.getElementById('data').innerText = text;
                setConnected(true)
            };

            source.onmessage = function (event) {
                let text = document.getElementById('data').innerText;
                text += '\nonmessage: ' + event.data;
                document.getElementById('data').innerText = text;
            };

            source.onerror = function (event) {
                // 未连接服务器, 执行操作逻辑
                if (event.type === 'error') {
                    alert("服务器连接失败,重试中...");
                    /* setTimeout(function () {
                         alert("服务器连接失败,重试中...");
                     }, 3000)*/
                }
            }
        } else {
            alert("你的浏览器不支持SSE");
        }
    }

    function sendMsg() {
        const userId = document.getElementById('userId').value;
        const targetId = document.getElementById('targetId').value;
        const msg = document.getElementById('msg').value;
        if (!targetId || !msg) {
            alert('对方ID或消息内容不能为空!');
            return;
        }

        // 创建一个post请求体
        const requestOptions = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                userId: userId,
                targetId: targetId,
                msg: msg
            }),
        };

        // 发送 POST 请求
        fetch(baseUrl + '/sse/sendMsg', requestOptions)
            .then(response => {
                if (!response.ok) {
                    throw new Error('请求失败!');
                }
                return response.json();
            })
            .then(data => {
                console.log('POST request successful:', data);
            })
            .catch(error => {
                console.error('POST request error:', error);
            });
    }

    function setConnected(connected) {
        if (connected) {
            document.getElementById('connect').disabled = true;
            document.getElementById('userId').disabled = true;
            document.getElementById('disconnect').disabled = false;
            document.getElementById('openChat').disabled = false;
        } else {
            document.getElementById('connect').disabled = false;
            document.getElementById('userId').disabled = false;
            document.getElementById('disconnect').disabled = true;
            document.getElementById('openChat').disabled = true;
            document.getElementById('chatBody').style.display = 'none';
        }
    }

    function openChat() {
        document.getElementById('chatBody').style.display = 'block';
        document.getElementById('openChat').style.display = 'none';
    }

    function sendGetRequest(url) {
        return fetch(url)
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.text();
            })
            .catch(error => {
                console.error('There was a problem with the fetch operation:', error);
            });
    }
</script>

